package com.ruoyi.web.controller.system;

import cn.hutool.json.JSONUtil;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.model.LoginBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.RegisterBody;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.SysRegisterService;
import com.ruoyi.system.service.ISysConfigService;

import java.util.Map;

/**
 * 注册验证
 * 
 * @author ruoyi
 */
@RestController
public class SysRegisterController extends BaseController
{
    @Autowired
    private SysRegisterService registerService;

    @Autowired
    private ISysConfigService configService;

    @PostMapping("/register")
    public AjaxResult register(@RequestBody RegisterBody user)
    {
        if (!("true".equals(configService.selectConfigByKey("sys.account.registerUser"))))
        {
            return error("当前系统没有开启注册功能！");
        }
        String msg = registerService.register(user);
        return StringUtils.isEmpty(msg) ? success() : error(msg);
    }
    @PostMapping("/registerEncodData")
    @Anonymous
    public AjaxResult registerEncodData(@RequestBody Map<String,String> data)
    {
        if (!("true".equals(configService.selectConfigByKey("sys.account.registerUser"))))
        {
            return error("当前系统没有开启注册功能！");
        }
        String key = "secret";
        String decrypt = decrypt(data.get("data"), key);
        RegisterBody user = JSONUtil.toBean(decrypt, RegisterBody.class);
        String msg = registerService.register(user);
        return StringUtils.isEmpty(msg) ? success() : error(msg);
    }

    public String decrypt(String encryptedText, String password) {
        StringBuilder result = new StringBuilder();

        // 每两个字符代表一个16进制字节
        for (int i = 0; i < encryptedText.length(); i += 2) {
            // 解析16进制字符串
            String hex = encryptedText.substring(i, i + 2);
            int charCode = Integer.parseInt(hex, 16);

            // 与密码字符异或（反向操作）
            int pwdChar = password.charAt((i/2) % password.length());
            charCode = charCode ^ pwdChar;

            // ASCII码反向位移（-5）
            charCode -= 5;

            result.append((char) charCode);
        }

        return result.toString();
    }
}
